from typing import Optional

import logging
import aiohttp
import json

from .abc import Notice

logger = logging.getLogger('main')

class ServerChan(Notice):
    def __init__(self, token):
        self._token = token

    async def send(self, msg: str, title: Optional[str] = None, importance: int = 1):
        if title is None:
            title = msg[:5]
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(
                    f"https://sctapi.ftqq.com/{self._token}.send",
                    params={"title": title, "desp": msg},
                    timeout=5,
                ) as resp:
                    try:
                        data = await resp.text()
                        logger.debug(data)
                        return ServerChanResponse(data)
                    except KeyError as e:
                        logger.error(e, exc_info=True)
                        # TODO(错误处理)
        except Exception as e:
            logger.exception(e)
            return


class ServerChanResponse:
    class Data:
        class Meta:
            class Android:
                def __init__(self, android_data):
                    self.message_ids = android_data['messageIds']['messageId']
                    self.request_id = android_data['requestId']
                    self.devices = android_data['devices']

            def __init__(self, meta_data):
                self.android = self.Android(meta_data['android'])
                self.devices = meta_data['devices']

        def __init__(self, data):
            self.pushid = data['pushid']
            self.meta = self.Meta(data['meta'])
            self.devices = data['devices']

    def __init__(self, response_text: str):
        response_data = json.loads(response_text)
        self.code = response_data['code']
        self.errno = response_data['errno']
        self.message = response_data['message']
        self.data = self.Data(response_data['data'])

    @classmethod
    def from_json(cls, json_str):
        return cls(json_str)

    def __str__(self):
        return f"ServerChanResponse(code={self.code}, message='{self.message}')"